package com.huazai.readwrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author huazai
 * @date 2024/2/4
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) {
        // 读 读  共享锁,大家都可以操作， 读写：独占锁，只能一个操作
        // 缺点：有锁的饥饿问题， 一直读，就没有写；一直写就没有读
        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
        reentrantReadWriteLock.readLock().lock();
        reentrantReadWriteLock.writeLock().lock();
        reentrantReadWriteLock.readLock().unlock();

        // 锁降级 获取读锁--》获取写锁--》释放度锁--》释放写锁  写锁降级为读锁
    }
}

class MyCache {
    private volatile Map<String, Object> map = new HashMap<>();

    public void add() {
        for (int i = 0; i < 5; i++) {
            map.put(String.valueOf(i), i);
            System.out.println("放入 i = " + i);
        }
    }
}
